import { Component, OnInit } from '@angular/core';
import { CheckService } from "../check.service";
import { Router, ActivatedRoute } from "@angular/router";
import { StorageService } from "../../../../common/storage.service";

@Component({
  selector: 'app-add-check',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.css'],
  providers: [CheckService]
})
export class AddCheckComponent implements OnInit {

  /**==================验收=======================*/
  title;  // 页签标题

  checkId;  // 验收项id
  checkManage: any = {};  // 验收项
  isWarningStatus = [];   // 是否预警
  selectedWarningStatus;  // 选择的项

  isEffects = [];  // 启用、禁用
  selectedisEffect;  // 选择的选项

  isCustomConfirm = [];  // 是否需要客户确认
  selectedConfirm;

  isCustomDiscussStatus = [];  // 是否需要客户评价
  selectedCustomDiscuss;  // 选择的选项

  isCustomBackStatus = []; // 是否客户回访
  selectedIsCustomBack;

  selectAlertMethod: string[] = [];  // 选中的提醒方式


  /**==================施工标准=======================*/
  conStandardList = [];  // 施工标准
  colsConStandard; // 施工标准列
  conStandardListForDel = [];  // 被删除施工标准

  /**==================验收标准=======================*/
  checkStandardList = [];   // 验收标准
  colsCheckStandard;  // 验收标准列

  isRequestPassItemArr = [];   // 是否为必过项
  checkStandardListForDel = [];  // 被删除验收标准

  /**=====================验证=======================*/
  checkCodeError;   // 验收项编号错误提示
  checkNameError;   // 验收项名称错误提示
  isWarningError;   // 是否预警错误提示
  warningDaysError;  // 预警天数错误提示
  isCustomConfirmError;  // 是否客户确认错误提示
  confirmDaysError;   // 自动确认天数错误提示
  selectAlertMethodError;  // 提醒方式
  isCustomDiscussError;   // 是否需要评价错误提示
  noDiscussAlertDaysError;  // 未评价提醒天数错误提示
  isCustomBackError;  // 是否客户回访错误提示
  isEffectError;  // 状态错误提示
  standardError; // 验收说明错误提示
  saddStandardError; // 验收标准错误提示
  loading; // 表格数据是否加载中


  constructor(private router: Router, private routeInfo: ActivatedRoute, private checkService: CheckService,
    private storage: StorageService) {
    // 验收-施工标准表头
    this.colsConStandard = [
      { field: 'sortNum', header: '序号', width: '46px', frozen: false, sortable: true, tem: true },
      { field: 'content', header: '施工标准', width: '500px', frozen: false, sortable: true, tem: true, editable: true, required: true },
      { field: 'operation', header: '操作', width: '180px', frozen: false, sortable: true, tem: true }
    ];
    // 验收-验收标准表头
    this.colsCheckStandard = [
      { field: 'sortNum', header: '序号', width: '90px', frozen: false, sortable: true, tem: true },
      { field: 'checkStandard', width: '335px', header: '验收标准', frozen: false, sortable: true, tem: true, editable: true, required: true },
      { field: 'checkItem', width: '175px', header: '检查项目', sortable: true, tem: true, editable: true },
      { field: 'phoneRequire', width: '110px', header: '照片/张', sortable: true, tem: true, editable: true, required: true },
      { field: 'tackPhoneRequire', width: '200px', header: '拍摄要求', sortable: true, tem: true, editable: true },
      { field: 'toolConfig', width: '170px', header: '基本配备工具', sortable: true, tem: true, editable: true },
      { field: 'isRequestPassItem', width: '170px', header: '是否为必过项', sortable: true, editable: true, tem: true },
      { field: 'operation', width: '180px', header: '操作', sortable: true, tem: true },
    ];
    let status = [{ 'name': '是', 'code': true }, { 'name': '否', 'code': false }];
    this.isWarningStatus = status;
    this.isCustomConfirm = status;
    this.isCustomDiscussStatus = status;
    this.isCustomBackStatus = status;
    this.isRequestPassItemArr = status;
    this.isEffects = [{ 'name': '启用', 'code': true }, { 'name': '禁用', 'code': false }]
  }

  ngOnInit() {
    this.storage.loading();
    // 获取路由id
    this.routeInfo.params.subscribe((params) => {
      this.checkId = params['id'];

      if (this.checkId) {
        this.title = '编辑验收';
        // 获取信息
        this.checkService.getCheckManageById(this.checkId).then(data => {
          this.storage.loadout();
          this.selectAlertMethod = [];
          this.checkManage = data.data.checkManage;
          this.selectedWarningStatus = this.checkManage['isWarning'] ? { 'name': '是', 'code': true } : { 'name': '否', 'code': false };
          this.selectedConfirm = this.checkManage['isCustomConfirm'] ? { 'name': '是', 'code': true } : { 'name': '否', 'code': false };
          this.selectedisEffect = this.checkManage['isEffect'] ? { 'name': '启用', 'code': true } : { 'name': '禁用', 'code': false };
          this.selectedCustomDiscuss = this.checkManage['isCustomDiscuss'] ? { 'name': '是', 'code': true } : { 'name': '否', 'code': false };
          this.selectedIsCustomBack = this.checkManage['isCustomBack'] ? { 'name': '是', 'code': true } : { 'name': '否', 'code': false };
          if (this.checkManage['alertMethod']) {
            this.checkManage['alertMethod'].split(',').forEach(am =>
              this.selectAlertMethod.push(am)
            )
          }
          this.conStandardList = data.data.conStandardList;
          this.checkStandardList = data.data.checkStandardList;
          this.checkStandardList.filter((item) => {
            item.isRequestPassItem = item['isRequestPassItem'] ? { 'name': '是', 'code': true } : { 'name': '否', 'code': false };
            return false;
          })
        });
      } else {
        this.storage.loadout();
        this.title = '创建验收';
        this.selectedWarningStatus = { 'name': '是', 'code': true };
        this.selectedConfirm = { 'name': '是', 'code': true };
        this.selectedisEffect = { 'name': '启用', 'code': true };
        this.selectedCustomDiscuss = { 'name': '是', 'code': true };
        this.selectedIsCustomBack = { 'name': '是', 'code': true };
        this.selectAlertMethod.push('alerttype_app');
      }
    });
  }

  //===================================================施工标准开始========================================================================
  //施工标准表格添加
  addConStandard() {
    //施工标准保存结果
    let conStandardListForSave = JSON.parse(JSON.stringify(this.conStandardList.concat(this.conStandardListForDel)));
    for (let item of conStandardListForSave) {
      if (!item['content']) {
        return;
      }
    }
    let standard = { sortNum: 1, content: '' };
    this.standardError = '';
    this.conStandardList = [...this.conStandardList, standard];
  }

  //施工标准上移
  conStandardMoveUp(index) {
    if (index == 0) {
      // this.error('已经是第一行了！');
      return;
    }
    let doc = this.conStandardList.splice(index, 1);
    this.conStandardList.splice(index - 1, 0, doc[0]);
    this.conStandardList = this.conStandardList.concat([])
  }

  //施工标准下移
  conStandardMoveDown(index) {
    if (index == this.conStandardList.length - 1) {
      // this.error('已经是最后一行了！');
      return;
    }
    let doc = this.conStandardList.splice(index, 1);
    this.conStandardList.splice(index + 1, 0, doc[0]);
    this.conStandardList = this.conStandardList.concat([])
  }

  /**
   *Description: 删除施工标准
   */
  removeConStandard(i) {
    let tec = this.conStandardList[i]
    if (tec.id) {
      tec.isDeleted = true;
      this.conStandardListForDel.push(tec)
    }
    this.conStandardList = this.conStandardList.filter((item, index) => {
      if (index === i) {
        return false;
      } else {
        return true;
      }
    })
  }
  //===================================================施工标准结束========================================================================


  //===================================================验收标准开始========================================================================
  //验收标准表格添加行
  addStandard() {
    //验收标准保存结果
    let checkStandardListForSave = JSON.parse(JSON.stringify(this.checkStandardList.concat(this.checkStandardListForDel)));
    for (let item of checkStandardListForSave) {
      if (!item['checkStandard']) {
        return;
      }
      if (!item['phoneRequire']) {
        return;
      }
    }
    let standard = {
      checkItem: "", checkStandard: "", isRequestPassItem: { 'name': '否', 'code': false }, phoneRequire: "",
      sortNum: 1, tackPhoneRequire: "", toolConfig: ""
    };
    this.saddStandardError = '';
    this.checkStandardList = [...this.checkStandardList, standard];
  }

  //验收标准上移
  checkStandardMoveUp(index) {
    if (index == 0) {
      // this.error('已经是第一行了！')
      return;
    }
    let doc = this.checkStandardList.splice(index, 1);
    this.checkStandardList.splice(index - 1, 0, doc[0]);
    this.checkStandardList = this.checkStandardList.concat([])
  }

  //验收标准下移
  checkStandardMoveDown(index) {
    if (index == this.checkStandardList.length - 1) {
      // this.error('已经是最后一行了！');
      return;
    }
    let doc = this.checkStandardList.splice(index, 1);
    this.checkStandardList.splice(index + 1, 0, doc[0]);
    this.checkStandardList = this.checkStandardList.concat([])
  }

  //删除验收标准
  removeCheckStandard(i) {
    let tec = this.checkStandardList[i]
    if (tec.id) {
      tec.isDeleted = true;
      this.checkStandardListForDel.push(tec)
    }
    this.checkStandardList = this.checkStandardList.filter((item, index) => {
      if (index === i) {
        return false;
      } else {
        return true;
      }
    })
  }
  //===================================================验收标准结束========================================================================
  //错误提示
  error(msg) {
    this.storage.messageService.emit({ severity: 'error', detail: msg })
  }

  //取消
  back() {
    if (this.checkId) {
      this.router.navigate(['saas/engineer/constructionconfig/check/', this.checkId]);
    } else {
      this.router.navigate(['saas/engineer/constructionconfig/check']);
    }
  }


  /**
   * Description: 保存验收项信息
   */
  save() {
    if (!this.checkId) {
      this.checkManage['isCustomConfirm'] = this.selectedConfirm.code;
      this.checkManage['isWarning'] = this.selectedWarningStatus.code;
      this.checkManage['isCustomDiscuss'] = this.selectedCustomDiscuss.code;
      this.checkManage['isCustomBack'] = this.selectedIsCustomBack.code;
    }
    //保存时二次验证
    if (!this.checkSaveData()) {
      return;
    }
    //施工标准保存结果
    let conStandardListForSave = JSON.parse(JSON.stringify(this.conStandardList.concat(this.conStandardListForDel)));
    for (let item of conStandardListForSave) {
      if (!item['content']) {
        return;
      }
    }
    //验收标准保存结果
    let checkStandardListForSave = JSON.parse(JSON.stringify(this.checkStandardList.concat(this.checkStandardListForDel)));
    for (let item of checkStandardListForSave) {
      if (!item['checkStandard']) {
        return;
      }
      if (!item['phoneRequire']) {
        return;
      }
    }
    checkStandardListForSave.filter((item) => {
      item.isRequestPassItem = item.isRequestPassItem['code'];
      return false;
    });

    if (this.selectAlertMethod) {
      this.checkManage['alertMethod'] = this.selectAlertMethod.join(',');
    } else {
      this.checkManage['alertMethod'] = null;
    }
    this.storage.loading();
    if (this.checkId) {
      if (!this.selectedisEffect && this.checkManage['isEffect'] == undefined) {
        return false;
      }
      this.checkService.updata({
        checkManage: this.checkManage, conStandardList: conStandardListForSave,
        checkStandardList: checkStandardListForSave
      }).then(
        data => {
          if (data.result) {
            this.storage.loadout();
            this.storage.messageService.emit({ severity: 'success', detail: data.msg });
            this.router.navigate(['saas/engineer/constructionconfig/check/', this.checkId]);
          } else {
            this.storage.loadout();
            this.storage.messageService.emit({ severity: 'error', detail: data.msg });
          }
        }
      );
    } else {
      this.checkService.save({
        checkManage: this.checkManage, conStandardList: conStandardListForSave,
        checkStandardList: checkStandardListForSave
      }).then(
        data => {
          if (data.result) {
            this.storage.loadout();
            this.storage.messageService.emit({ severity: 'success', detail: data.msg });
            this.router.navigate(['saas/engineer/constructionconfig/check']);
          } else {
            this.storage.loadout();
            this.storage.messageService.emit({ severity: 'error', detail: data.msg });
          }
        }
      );
    }
  }


  /**================================================验证==========================================================================*/

  /**
   * Description: 编号唯一性验证
   */
  checkCodeCk() {
    this.checkManage['code'] = this.checkManage['code'] ? this.checkManage['code'].trim() : '';
    if (!this.checkManage['code']) {
      this.checkCodeError = '请输入编号';
    } else {
      if (this.checkManage['code'].length > 20) {
        this.checkCodeError = '最多20个字符!';
      } else {
        this.checkService.uniqueCode({ 'code': this.checkManage['code'], "checkId": this.checkId }).then(data => {
          if (data.result) {
            this.checkCodeError = '';
          } else {
            this.checkCodeError = data.msg;
          }
        });
        this.checkCodeError = '';
      }
    }
  }

  /**
   * Description: 验收项名称唯一性验证
   */
  checkNameCk() {
    this.checkManage['name'] = this.checkManage['name'] ? this.checkManage['name'].trim() : '';
    if (!this.checkManage['name']) {
      this.checkNameError = '请输入名称';
    } else {
      if (this.checkManage['name'].length > 25) {
        this.checkNameError = '最多25个字符';
      } else {
        this.checkService.uniqueName({ 'name': this.checkManage['name'], "checkId": this.checkId }).then(data => {
          if (data.result) {
            this.checkNameError = '';
          } else {
            this.checkNameError = data.msg;
          }
        });
        this.checkNameError = '';
      }
    }
  }



  /**
   * Description: 是否预警验证
   */
  isWarningStatusCk() {
    if (!this.selectedWarningStatus) {
      this.isWarningError = '请输入是否预警';
    } else {
      this.checkManage['isWarning'] = this.selectedWarningStatus.code;
      this.isWarningError = '';
      if (!this.selectedWarningStatus.code) {
        this.checkManage['warningDays'] = 0;
        this.warningDaysError = '';
      }
    }
  }

  /**
   * Description: 预警天数不能为空
   */
  warningDaysCk() {
    if (this.selectedWarningStatus && this.selectedWarningStatus.code) {
      let warningDays = this.checkManage['warningDays'];
      if (warningDays == null || Number(warningDays) < 0) {
        this.warningDaysError = '请输入预警天数';
      }
    } else {
      this.checkManage['warningDays'] = 0;
      this.warningDaysError = '';
    }
  }

  /**
   * Description: 是否客户确认验证
   */
  isCustomConfirmCk() {
    if (!this.selectedConfirm) {
      this.isCustomConfirmError = '请输入是否客户确认';
    } else {
      this.checkManage['isCustomConfirm'] = this.selectedConfirm.code;
      this.isCustomConfirmError = '';
      if (!this.selectedConfirm.code) {
        this.checkManage['confirmDays'] = 0;
        this.confirmDaysError = '';
      }
    }
  }

  /**
   * Description: 自动确认天数验证
   */
  confirmDaysCk() {
    if (this.selectedConfirm && this.selectedConfirm.code) {
      let confirmDays = this.checkManage['confirmDays'];
      if (confirmDays == null || Number(confirmDays) < 0) {
        this.confirmDaysError = '请输入自动确认天数';
      }
    } else {
      this.checkManage['confirmDays'] = 0;
      this.confirmDaysError = '';
    }
  }

  /**
   * Description: 提醒方式
   */
  // clickSelectAlertMethod() {
  //   this.selectAlertMethodError = false;
  // }
  // clickSelectAlertMethodApp() {

  // }
  /**
   * Description: 是否需要评价
   */
  isCustomDiscussCk() {
    if (!this.selectedCustomDiscuss) {
      this.isCustomDiscussError = '请输入是否需要评价';
    } else {
      this.checkManage['isCustomDiscuss'] = this.selectedCustomDiscuss.code;
      this.isCustomDiscussError = '';
      if (!this.selectedCustomDiscuss.code) {
        this.checkManage['noDiscussAlertDays'] = 0;
        this.noDiscussAlertDaysError = '';
      }
    }
  }

  /**
   * Description: 未评价提醒天数验证
   */
  noDiscussAlertDaysCk() {
    if (this.selectedCustomDiscuss && this.selectedCustomDiscuss.code) {
      let noDiscussAlertDays = this.checkManage['noDiscussAlertDays'];
      if (noDiscussAlertDays == null || Number(noDiscussAlertDays) < 0) {
        this.noDiscussAlertDaysError = '请输入未评价提醒天数';
      }
    } else {
      this.checkManage['noDiscussAlertDays'] = 0;
      this.noDiscussAlertDaysError = '';
    }
  }

  /**
   * Description: 是否客户回访
   */
  isCustomBackCk() {
    if (!this.selectedIsCustomBack) {
      this.isCustomBackError = '请输入客户回访';
    } else {
      this.checkManage['isCustomBack'] = this.selectedIsCustomBack.code;
      this.isCustomBackError = '';
    }
  }

  /**
   * Description: 状态验证
   */
  isEffectCk() {
    if (!this.selectedisEffect) {
      this.isEffectError = '请输入状态';
    } else {
      this.checkManage['isEffect'] = this.selectedisEffect.code;
      this.isEffectError = '';
    }
  }

  /**
   * Description: 验收标准必填项验证
   */
  checkStandrad() {
    let checkStandards = this.checkStandardList;
    if (checkStandards.length == 0) {
      return false
    }
    for (let index of this.checkStandardList) {
      if (!index.checkStandard || !index.phoneRequire || index.isRequestPassItem == undefined) {
        return false;
      }
    }
    return true;
  }

  // 保存时校验
  checkSaveData(): boolean {
    let flag = true;
    if (!this.checkManage['code']) {
      flag = false;
      this.checkCodeError = '请输入编号';
    } else {
      this.checkCodeError = '';
    }
    if (!this.checkManage['name']) {
      flag = false;
      this.checkNameError = '请输入名称';
    } else {
      this.checkNameError = '';
    }
    if (this.checkManage['isWarning'] == undefined) {
      flag = false;
      this.isWarningError = '请选择是否预警';
    } else {
      this.isWarningError = '';
    }
    if (this.checkManage['isCustomConfirm'] == undefined) {
      flag = false;
      this.isCustomConfirmError = '请选择是否客户确认';
    } else {
      this.isCustomConfirmError = '';
    }
    if (this.checkManage['isCustomBack'] == undefined) {
      flag = false;
      this.isCustomBackError = '请选择是否客户回访';
    } else {
      this.isCustomBackError = '';
    }
    if (this.checkManage['isCustomDiscuss'] == undefined) {
      flag = false;
      this.isCustomDiscussError = '请选择是否需要评价';
    } else {
      this.isCustomDiscussError = '';
    }
    if (this.conStandardList.length == 0) {
      flag = false;
      this.standardError = '请添加验收说明';
    } else {
      this.standardError = '';
    }
    if (this.checkStandardList.length == 0) {
      flag = false;
      this.saddStandardError = '请添加验收标准';
    } else {
      this.saddStandardError = '';
    }
    if (this.checkManage['isWarning'] && (this.checkManage['warningDays'] == null || Number(this.checkManage['warningDays']) < 0)) {
      flag = false;
      this.warningDaysError = '请输入预警天数';
    } else {
      this.warningDaysError = '';
    }
    if (this.checkManage['isCustomConfirm'] && (this.checkManage['confirmDays'] == null || Number(this.checkManage['confirmDays']) < 0)) {
      flag = false;
      this.confirmDaysError = '请输入自动确认天数';
    } else {
      this.confirmDaysError = '';
    }
    if (this.checkManage['isCustomDiscuss'] && (this.checkManage['noDiscussAlertDays'] == null
      || Number(this.checkManage['noDiscussAlertDays']) < 0)) {
      flag = false;
      this.noDiscussAlertDaysError = '请输入未评价提醒天数';
    } else {
      this.noDiscussAlertDaysError = '';
    }
    return flag;
  }
  // 施工标准提示
  checkContentIsNull(data) {
    if (!data) {
      return '请输入验收标准';
    } else {
      if (data.length > 100) {
        return '最大长度100';
      }
    }

  }
  // 施工标准红框显示
  checkContent(data) {
    if (!data) {
      return true;
    } else {
      if (data.length > 100) {
        return true;
      }
    }
    return false;
  }
  // 验收标准照片/张提示
  checkPgotosIsNull(photos) {
    if (!photos) {
      return '请输入照片/张';
    } else {
      if (photos.length > 5) {
        return '最大长度5';
      } else {
        if (isNaN(photos)) {
          return '请输入正确的照片/张';
        }
      }
    }

  }
  // 验收标准照片/张 红框显示
  checkPhotos(photos) {
    if (!photos) {
      return true;
    } else {
      if (photos.length > 5) {
        return true;
      } else {
        if (isNaN(photos)) {
          return true;
        }
      }
    }
    return false;
  }
  // 验收标准提示
  checkStandardIsNull(data) {
    if (!data) {
      return '请输入验收标准';
    } else {
      if (data.length > 100) {
        return '最大长度100';
      }
    }

  }
  // 验收标准红框显示
  checkStandard(data) {
    if (!data) {
      return true;
    } else {
      if (data.length > 100) {
        return true;
      }
    }
    return false;
  }
}
